//定义一个常亮key，将来操作这个localstrage中的数据
export const KEY = 'goodsdata';

export var valueObj = {goodsid:0,count:0};

//设置数据
export function setItem(value){
    var jsonString = localStorage.getItem(KEY);
    jsonString = jsonString || '[]';
    var arr = JSON.parse(jsonString);
    //将value追加到arr
    arr.push(value);
    //将arr转化成jsonp字符串保存起来
    localStorage.setItem(KEY,JSON.stringify(arr));
}

//获取数据
export function getItem(){
    var jsonString = localStorage.getItem(KEY);
    jsonString = jsonString || '[]';
    return JSON.parse(jsonString);
}

//删除数据
export function removeItem(goodsid){
    var arr = getItem();
    for(var i = arr.length-1;i>=0;i--){
        if(arr[i].goodsid == goodsid){
            arr.splice(i,1)
        }
    }
    //将最新数据储存在local
    localStorage.setItem(KEY,JSON.stringify(arr));
}

//将localStorage里面的数据转化成对象
export function getgoodsObj(){
    var arr = getItem();
    var res = {};
    for(var i = 0;i<arr.length;i++){
        var item = arr[i];
        if(!res[item.goodsid]){
            res[item.goodsid] = item.count;
        }else {
            var count = res[item.goodsid];
            res[item.goodsid] = item.count + count
        }
    }
    return res ;
}
//看传进来的是加还是减的功能
export function updataData(obj){
    var arr = getItem();
    var count = 1;
    if(obj.type == 'add'){
        //加
        arr.push({goodsid:obj.goodsid,count:count});
    }else {
        for(var i = 0;i<arr.length;i++){
            if(arr[i].goodsid == obj.goodsid){
                if(arr[i].count>1){
                    arr[i].count = arr[i].count -1;
                    break;
                }else{
                    arr.splice(i,1);
                    break;
                }
            }
        }
    }
    //将最新的数据储存到local中
    localStorage.setItem(KEY,JSON.stringify(arr));
}